package cn.wolfcode.trip.base.service.impl;

import cn.wolfcode.trip.base.domain.StrategyContent;
import cn.wolfcode.trip.base.domain.StrategyDetail;
import cn.wolfcode.trip.base.mapper.StrategyContentMapper;
import cn.wolfcode.trip.base.mapper.StrategyDetailMapper;
import cn.wolfcode.trip.base.query.QueryObject;
import cn.wolfcode.trip.base.service.IStrategyDetailService;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.xml.crypto.Data;
import java.util.Date;
import java.util.List;

@Service
public class StrategyDetailServiceImpl implements IStrategyDetailService{
    @Autowired
    private StrategyDetailMapper detailMapper;
    @Autowired
    private StrategyContentMapper contentMapper;

    public PageInfo<?> query(QueryObject qo) {
        qo.setOrderBy("sd.releaseTime desc");
        PageHelper.startPage(qo.getCurrentPage(),qo.getPageSize(),qo.getOrderBy());
        List<StrategyDetail> list = detailMapper.queryForList(qo);
        return new PageInfo<>(list);
    }

    public void saveOrUpdate(StrategyDetail detail) {
        if (detail.getSequence() == null){
            int sequence = detailMapper.selectMaxSequence(detail.getCatalog().getId());
            if (sequence == 0){
                detail.setSequence(sequence);
            }else {
                detail.setSequence(sequence+1);
            }
        }
        StrategyContent strategyContent = new StrategyContent();
        if (detail.getId() == null){
            Date date = new Date();
            detail.setCreateTime(date);
            if (detail.getState() == 0){
                detail.setReleaseTime(date);
            }
            detailMapper.insert(detail);
            strategyContent.setId(detail.getId());
            strategyContent.setContent(detail.getStrategyContent().getContent());
            contentMapper.insert(strategyContent);
        }else {
            detailMapper.updateByPrimaryKey(detail);
            strategyContent.setId(detail.getId());
            strategyContent.setContent(detail.getStrategyContent().getContent());
            contentMapper.updateByPrimaryKey(strategyContent);
        }
    }

    public StrategyDetail getContentById(Long detailId) {
        return detailMapper.selectByPrimaryKey(detailId);
    }
}
